<template>
    <view class="life-payment-container" id="boxH">
        <header-vue :back="true" title="生活缴费" titleColor="#333" titleSize="32rpx" id="headerH">
            <template v-slot:btnLt>
                <text class="font30 btn-text" @click="gotoUrl('/views/index/payment-record')">缴费记录</text>
            </template>
        </header-vue>
        
        <!-- 主要内容区域 -->
        <scroll-view 
            class="scroll-content"
            :style="{'height':sH + 'px'}"
            scroll-y
            :refresher-enabled="true"
            :refresher-triggered="refreshing"
            @refresherrefresh="onRefresh"
            @scrolltolower="onLoadMore"
            :lower-threshold="100"
            refresher-background="transparent"
        >
            <!-- 地址信息 -->
            <view class="address-section">
                <view class="address-card">
                    <view class="address-icon">
                        <i class="iconfont icon-dizhi font30"></i>
                    </view>
                    <text class="address-text">华望城悦华园二区34号楼4-404</text>
                </view>
            </view>
            
            <!-- 账单列表 -->
            <view class="bill-list">
                <u-checkbox-group v-model="selectedBillsValue" @change="onBillChange" placement="column">
                    <view 
                        class="bill-item" 
                        v-for="(bill, index) in billList" 
                        :key="bill.year"
                    >
                        <view class="bill-content">
                            <view class="bill-checkbox">
                                <u-checkbox 
                                    :name="bill.year"
                                    :disabled="false"
                                    activeColor="#4A90E2"
                                    shape="circle"
                                    size="30rpx"
                                ></u-checkbox>
                            </view>
                            <view class="bill-year">{{ bill.year }}年</view>
                        </view>
                        <view class="bill-type-box">
                            <view class="bill-type flex">
                                <view class="bill-type-icon">
                                    <i class="iconfont icon-shenghuo font30"></i>
                                </view>
                                <text class="bill-type-text">生活缴费</text>
                            </view>
                            <view class="bill-amount">
                                <text class="amount-text">合计:¥{{ bill.amount }}</text>
                            </view>
                        </view>
                    </view>
                </u-checkbox-group>
            </view>
            
            <!-- 加载更多提示 -->
            <view class="load-more" v-if="loading">
                <u-loading-icon mode="circle" size="24"></u-loading-icon>
                <text class="load-text">加载中...</text>
            </view>
        </scroll-view>
        
        <!-- 底部支付栏 -->
        <fixed-footer id="fixedFooterH">
            <view class="payment-footer">
                <u-checkbox-group v-model="selectAllValue" @change="onSelectAllChange">
                    <view class="select-all">
                        <u-checkbox 
                            name="selectAll"
                            :disabled="false"
                            activeColor="#4A90E2"
                            shape="circle"
                            size="36rpx"
                        ></u-checkbox>
                        <text class="select-all-text">全部</text>
                    </view>
                </u-checkbox-group>
                <view class="lr-box flex between">
                    <view class="total-amount">
                        <view class="font28 total-txt">合计:</view>
                        <view class="flex" v-if="totalAmount && totalAmount.toString().includes('.')">
                            <view class="font28">￥</view>
                            <view class="font36">{{ totalAmount.toString().split('.')[0] }}</view>
                            <view class="font28">.{{ totalAmount.toString().split('.')[1] }}</view>
                        </view>
                        <view class="flex" v-else>
                            <view class="font28">￥</view>
                            <view class="font36">{{ totalAmount || '0' }}</view>
                            <view class="font28">.00</view>
                        </view>
                    </view>
                    <view class="pay-button" @click="showPayPopup">
                        <text class="font36">去缴费</text>
                    </view>
                </view>
            </view>
        </fixed-footer>
        
        <!-- 支付弹窗 -->
        <order-pay-popup
            :show="showPay"
            :amount="parseFloat(payAmount)"
            :balance="userBalance"
            @update:show="showPay = $event"
            @confirm="onPayConfirm"
            :isVirtual="true"
            @virtualEvent="virtualEvent"
            :virtualAssetText="virtualAssetText"
        ></order-pay-popup>

        <!-- 虚拟资产 -->
        <virtual-asset-popup 
            :show.sync="showVirtualAssetPopup"
            :assets="virtualAssets"
            :defaultSelected="selectedAsset || ''"
            @assetsReady="onAssetsReady"
            @confirm="onAssetConfirmed"
        />
    </view>
</template>
<script>
import headerVue from '@/components/header.vue';
import fixedFooter from '@/components/fixed-footer/index.vue';
import orderPayPopup from '@/components/order/pay.vue';
import virtualAssetPopup from '@/components/virtual-asset-popup/index.vue' 

export default {
    components: {
        headerVue,
        fixedFooter,
        orderPayPopup,
        virtualAssetPopup
    },
    data() {
        return {
            refreshing: false,
            loading: false,
            showPay: false,
            userBalance: 1000, // 用户余额
            billList: [
                { year: 2026, amount: 500.00, selected: false },
                { year: 2025, amount: 500.00, selected: false },
                { year: 2024, amount: 500.00, selected: false },
                { year: 2023, amount: 500.00, selected: false },
            ],
            selectedBillsValue: [], // checkbox-group的值，默认选中2026年
            selectAllValue: [], // 全选checkbox的值
            sH: 0,
            virtualAssetText:'请选择',
            // 虚拟资产弹窗与抵扣
            showVirtualAssetPopup: false,
            virtualAssets: null,
            selectedAsset: '',
            virtualAssetAmount: 0,
            _openedFromPay: false
        }
    },
    computed: {
        selectedBills() {
            return this.billList.filter(bill => this.selectedBillsValue.includes(bill.year));
        },
        totalAmount() {
            return this.selectedBills.reduce((total, bill) => {
                return total + bill.amount;
            }, 0).toFixed(2);
        },
        // 抵扣后的支付金额
        payAmount() {
            const finalAmt = Number(this.totalAmount || 0) - Number(this.virtualAssetAmount || 0)
            return (finalAmt > 0 ? finalAmt : 0).toFixed(2)
        },
        isAllSelected() {
            return this.billList.length > 0 && this.billList.every(bill => this.selectedBillsValue.includes(bill.year));
        }
    },
    mounted() {
        // 获取系统信息计算高度，兼容App端
        const systemInfo = uni.getSystemInfoSync()
        // App端使用screenHeight，H5端使用windowHeight
        const screenHeight = systemInfo.screenHeight || systemInfo.windowHeight
        const statusBarHeight = systemInfo.statusBarHeight || 0
        
        // 延迟执行确保DOM渲染完成，App端需要更长时间
        setTimeout(() => {
            const q = uni.createSelectorQuery().in(this)
            q.select('#headerH').boundingClientRect()
             .select('#fixedFooterH').boundingClientRect()
             .exec(rects => {
                if (!rects || rects.length < 2) {
                    // 如果获取失败，使用默认值
                    this.sH = screenHeight - statusBarHeight
                    return
                }
                
                const headerRect = rects[0]
                const fixedFooterRect = rects[1]
                const headerHeight = headerRect ? headerRect.height : 88
                const fixedFooterH = fixedFooterRect ? fixedFooterRect.height : 120
                
                // App端计算：屏幕高度 - 状态栏 - header - footer
                const calc = screenHeight - headerHeight - fixedFooterH
                
                this.sH = calc > 0 ? calc : screenHeight - statusBarHeight
              })
        }, 200) // App端需要更长的延迟
        
        // 初始化全选checkbox状态
        this.updateSelectAllStatus()
    },
    methods: {
        gotoUrl(url){
            uni.navigateTo({url: url})
        },
        // 打开虚拟资产弹窗（从支付弹窗进入）
        virtualEvent() {
            this._openedFromPay = true
            this.showPay = false
            this.showVirtualAssetPopup = true
        },
        // 虚拟资产数据准备
        onAssetsReady(assets) {
            this.virtualAssets = assets
        },
        // 虚拟资产选择确认
        onAssetConfirmed(assetType, assets) {
            this.selectedAsset = assetType
            this.virtualAssets = assets
            if (assetType === 'points') {
                // 根据需求处理积分，这里默认不抵扣
                this.virtualAssetAmount = 0
                this.virtualAssetText = `-${assets.points}`
            } else if (assetType === 'warmCore') {
                // 暖芯值按1:1抵扣，最多不超过应付金额
                const canUse = Math.min(Number(assets.warm_core || 0), Number(this.totalAmount || 0))
                this.virtualAssetAmount = canUse
                this.virtualAssetText = `-${canUse}`
            }
            // 关闭资产弹窗并回到支付弹窗
            this.showVirtualAssetPopup = false
            this.showPay = true
        },
        // checkbox-group变化事件
        onBillChange(value) {
            this.selectedBillsValue = value;
            // 更新全选checkbox状态
            this.updateSelectAllStatus();
        },
        
        // 全选checkbox变化事件
        onSelectAllChange(value) {
            this.selectAllValue = value;
            if (value.includes('selectAll')) {
                // 全选：选中所有账单
                this.selectedBillsValue = this.billList.map(bill => bill.year);
            } else {
                // 取消全选：清空选中
                this.selectedBillsValue = [];
            }
        },
        
        // 更新全选checkbox状态
        updateSelectAllStatus() {
            if (this.isAllSelected) {
                this.selectAllValue = ['selectAll'];
            } else {
                this.selectAllValue = [];
            }
        },
        
        // 下拉刷新
        onRefresh() {
            this.refreshing = true;
            setTimeout(() => {
                this.refreshing = false;
                uni.showToast({
                    title: '刷新成功',
                    icon: 'success'
                });
            }, 1500);
        },
        
        // 触底加载
        onLoadMore() {
            if (this.loading) return;
            this.loading = true;
            setTimeout(() => {
                this.loading = false;
                // 这里可以添加更多账单数据
                uni.showToast({
                    title: '已加载全部',
                    icon: 'none'
                });
            }, 1000);
        },
        
        // 显示支付弹窗
        showPayPopup() {
            if (this.selectedBills.length === 0) {
                uni.showToast({
                    title: '请选择要缴费的账单',
                    icon: 'none'
                });
                return;
            }
            this.showPay = true;
        },
        
        // 确认支付
        onPayConfirm(payData) {
            console.log('支付信息:', payData);
            uni.showLoading({
                title: '支付中...'
            });
            
            // 模拟支付过程
            setTimeout(() => {
                uni.hideLoading();
                this.showPay = false;
                uni.showToast({
                    title: '支付成功',
                    icon: 'success'
                });
                
                // 支付成功后清空选中状态
                this.selectedBillsValue = [];
                uni.reLaunch({url:'/views/index/success?id=123465'})
            }, 2000);
        }
    }
}
</script>
<style lang="scss" scoped>
.life-payment-container {
    width: 100%;
    height: 100%;
    background: #F6F6F6;
    
    .btn-text {
        font-size: 28rpx;
        color: #DF9824;
    }
}

.scroll-content {
    flex: 1;
}

.address-section {
    padding: 28rpx 32rpx;
    
    .address-card {
        border-radius: 16rpx;
        display: flex;
        align-items: center;
        
        .address-icon {
            margin-right: 10rpx;
            color: #DF9824;
        }
        
        .address-text {
            font-size: 28rpx;
            color: #333;
        }
    }
}

.bill-list {
    padding: 0 32rpx;
    
    .bill-item {
        background: #fff;
        border-radius: 16rpx;
        padding: 28rpx;
        margin-bottom: 28rpx;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
        
        
        .bill-content {
            flex: 1;
            display: flex;
            align-items: center;
            
            .bill-year {
                font-size: 32rpx;
                color: #333;
                font-weight: 600;
            }
           
        }

        .bill-type-box {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding-left: 40rpx;
                margin-top: 28rpx;
            }
            
            .bill-type {
                display: flex;
                align-items: center;

                .bill-type-icon {
                    width: 48rpx;
                    height: 48rpx;
                    background: #EDF8FF;
                    border-radius: 12rpx 12rpx 12rpx 12rpx;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    margin-right: 10rpx;
                    color: #0785CF;
                }
                
                .bill-type-text {
                    font-size: 28rpx;
                    color: #333;
                }
            }
        
        .bill-amount {
            .amount-text {
                font-size: 28rpx;
                color: #FF4D4F;
                font-weight: 600;
            }
        }
    }
}

.load-more {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 24rpx;
    
    .load-text {
        font-size: 24rpx;
        color: #999;
        margin-left: 12rpx;
    }
}

.payment-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16rpx 0;
    
    .select-all {
        display: flex;
        align-items: center;
        margin-right: 24rpx;
        
        .select-all-text {
            font-size: 28rpx;
            color: #333;
            margin-left: 8rpx;
        }
    }
    
    .total-amount {
        font-size: 28rpx;
        color: #FF4D4F;
        display: flex;
        align-items: baseline;

        .total-txt {
            color: #000;
        }

        .flex {
            align-items: baseline;
        }
    }
    
    .pay-button {
        width: 228rpx;
        height: 76rpx;
        background: linear-gradient( 90deg, #0785CF 0%, #25A4EF 100%);
        border-radius: 76rpx;
        text-align: center;
        color: #fff;
        line-height: 76rpx;
        font-weight: bold;
        margin-left: 32rpx;
    }
}
</style>